package com.xzj.admin.boot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xzj.admin.boot.domain.vo.SysDeptVO;
import com.xzj.common.core.utils.TreeUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.xzj.common.datasource.domain.PageReq;
import com.xzj.common.datasource.domain.PageResp;
import com.xzj.common.datasource.utils.XzjPageUtil;
import com.xzj.admin.boot.domain.entity.SysDept;
import com.xzj.admin.boot.mapper.SysDeptMapper;
import com.xzj.admin.boot.service.SysDeptService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: xzj-admin
 * @ClassName: SysDeptServiceImpl
 * @description: 部门表;(sys_dept)表服务实现类
 * @author: XiaZunJun
 * @create: 2024-7-30
 */
@Service
public class SysDeptServiceImpl implements SysDeptService{
    @Resource
    private SysDeptMapper sysDeptMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param deptId 主键
     * @return 实例对象
     */
    public SysDept queryById(long deptId){
        return sysDeptMapper.queryById(deptId);
    }

    /**
     * 分页查询
     *
     * @param pageReq 分页筛选条件对象
     * @return 查询结果
     */
    public PageResp<SysDept> pageQuery(PageReq<SysDept> pageReq){
        return XzjPageUtil.queryPage(pageReq, sysDept -> sysDeptMapper.queryAllByLimit(sysDept));
    }

    @Override
    public Map<String, String> deptMap(SysDept sysDept) {
        List<SysDept> sysDepts = sysDeptMapper.queryAllByLimit(sysDept);
        return TreeUtil.treeToMap(sysDepts, SysDept::getDeptId, SysDept::getParentDept, SysDept::getDeptName);
    }

    /**
     * 新增数据
     *
     * @param sysDept 实例对象
     * @return 实例对象
     */
    public SysDept insert(SysDept sysDept){
        sysDeptMapper.insert(sysDept);
        return sysDept;
    }

    /**
     * 更新数据
     *
     * @param sysDept 实例对象
     * @return 实例对象
     */
    public SysDept update(SysDept sysDept){
        sysDeptMapper.update(sysDept);
        return sysDept;
    }

    /**
     * 通过主键删除数据
     *
     * @param deptId 主键
     * @return 是否成功
     */
    public boolean deleteById(long deptId){
        int total = sysDeptMapper.deleteById(deptId);
        return total > 0;
    }

    @Override
    public boolean delete(SysDept sysDept) {
        if(StrUtil.isEmpty(sysDept.getDeptId())){
            return false;
        }
        int total = sysDeptMapper.deleteById(Long.parseLong(sysDept.getDeptId()));
        return total > 0;
    }

    @Override
    public List<SysDeptVO> getDeptList(SysDept sysDept) {
        List<SysDeptVO> sysDeptList = sysDeptMapper.queryDeptList(sysDept);
        return TreeUtil.listToTree(sysDeptList, SysDeptVO::getDeptId, SysDeptVO::getParentDept);
    }
}